import express from "express";
import { PrismaClient, mp_role as PRole } from "@prisma/client";
import { CreateId, Check, Result, Time, Utils } from "@/utils";

const prisma = new PrismaClient();
const router = express.Router();

router.post("/create", async (req, res) => {
   const { account, role_id, phone, name }: User.Create = req.body;
   if (!Check.Required([role_id, phone])) return res.send(Result.Error("参数错误"));

   const user = await prisma.user.findMany({ where: { phone } });
   if (user.length > 0) return res.send(Result.Error("当前手机号码已被注册"));

   const salt = Utils.GenerateSalt();
   const id = await CreateId.One("user");

   await prisma.user.create({
      data: {
         id,
         salt,
         phone,
         role_id,
         name: name || null,
         account: account || phone,
         status: "NOT_ACTIVATED",
         created_time: Time.Now()
      }
   });

   res.send(Result.OK());
});

router.post("/delete", async (req, res) => {
   const { userId } = req.body;
   if (!Check.Required([userId])) return res.send(Result.Error("参数错误"));

   const user = await prisma.user.findUnique({ where: { id: userId } });
   if (!user) return res.send(Result.Error("当前用户不存在"));

   const role = await prisma.mp_role.findUnique({ where: { id: user.role_id } });
   if (!role) return res.send(Result.Error());

   if (role.super_admin) return res.send(Result.Error("超级管理员角色不可删除"));

   await prisma.user.delete({ where: { id: userId } });

   return res.send(Result.OK());
});

router.post("/update", async (req, res) => {
   const { id, account, role_id, phone, name, status }: User.Update = req.body;
   if (!Check.Required([id, role_id, phone, status])) return res.send(Result.Error("参数错误"));

   // start --- 确保超级管理员只能有一个用户
   // 查询当前角色信息
   const role = await prisma.mp_role.findUnique({ where: { id: role_id } });

   if (!role) return res.send(Result.Error("角色不存在"));

   // 如果当前角色为超级管理员
   if (role.super_admin) {
      // 查询是否存在当前角色的用户
      const userList = await prisma.user.findMany({ where: { role_id } });
      if (userList.length > 0) {
         if (userList[0].id != id) return res.send(Result.Error("超级管理员角色只能分配给一个用户"));
      }
   }

   // end --- 确保超级管理员只能有一个用户

   await prisma.user.update({
      where: { id },
      data: {
         account,
         role_id,
         phone,
         name,
         status
      }
   });
   res.send(Result.OK());
});

router.get("/search", async (req, res) => {
   const userList = await prisma.user.findMany({
      select: {
         account: true,
         id: true,
         name: true,
         status: true,
         role_id: true,
         created_time: true,
         phone: true
      }
   });

   const role = await prisma.mp_role.findMany();

   const roleMap = new Map<string, PRole>();

   role.forEach(item => {
      roleMap.set(item.id, item);
   });

   const list = userList.map(item => {
      return {
         ...item,
         role_name: roleMap.get(item.role_id)?.name || null,
         created_time: Time.Format(item.created_time)
      };
   });

   res.send(Result.OK(list));
});

/** 激活用户 */
router.post("/action", async (req, res) => {
   const { userId } = req.body;
   if (!Check.Required([userId])) return res.send(Result.Error("参数错误"));

   const user = await prisma.user.findUnique({ where: { id: userId } });

   if (!user) return res.send(Result.Error("当前用户不存在"));
   if (user.status != "NOT_ACTIVATED") return res.send(Result.Error("当前用户已激活或已注销"));

   await prisma.user.update({ where: { id: userId }, data: { status: "NORMAL" } });

   res.send(Result.OK());
});

/** 重置密码 */
router.post("/password/reset", async (req, res) => {
   const { user_id, pwd }: User.Password.Reset = req.body;
   if (!Check.Required([user_id])) return res.send(Result.Error("参数错误"));

   const user = await prisma.user.findFirst({ where: { id: user_id, status: { not: "LOGINOUT" } } });

   if (!user) return res.send(Result.Error("当前用户不存在或已注销"));

   const newPwd = pwd ? pwd : "Ab12345678";
   const password = Utils.GeneratePWD(newPwd, user.salt);

   await prisma.user.update({
      where: { id: user_id },
      data: { password }
   });

   res.send(Result.OK());
});

export const user = router;
